﻿using Inovout.Services;
using System;
using System.ComponentModel.DataAnnotations;

namespace Inovout.Models
{
    [AttributeUsage(AttributeTargets.Property)]
    public class UniqueAttribute : ValidationAttribute
    {
        public string PropertyName { get; set; }
        public UniqueAttribute(string propertyName)
        {
            this.PropertyName = propertyName;
        }
        public string FormatAdditionalFields(string propertyName)
        {
            return "Id," + propertyName;
        }
        protected virtual IRepositoryService GetRepositoryService(Type modelType)
        {
            Type respositoryServiceType = typeof(IRepositoryService<>);
            respositoryServiceType = respositoryServiceType.MakeGenericType(modelType);
            return ComponentRegistry.Resolve<IRepositoryService>(respositoryServiceType);
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            DataObjectTypeDescriptor dataObjectTypeDescriptor = DataObjectTypeDescriptor.Get(validationContext.ObjectType);
            object id = dataObjectTypeDescriptor.IdentifierProperty.GetValue(validationContext.ObjectInstance);
            IRepositoryService repositoryService = GetRepositoryService(validationContext.ObjectType);
            if (!repositoryService.IsUnique(id, validationContext.MemberName ?? PropertyName, value))
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
            return null;
        }
    }
}
